import datetime
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Author, Book, Review, UserProfile, Genre
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class RenewBookForm(forms.Form):
    renewal_date = forms.DateField(
        help_text="输入一个在现在到4周内的日期（默认3周）。"
    )

    def clean_renewal_date(self):
        data = self.cleaned_data['renewal_date']
        
        # 检查日期是否为过去的日期
        if data < datetime.date.today():
            raise ValidationError(_('无效日期 - 续借日期在过去'))
            
        # 检查日期是否在允许范围内（今天 + 4周）
        if data > datetime.date.today() + datetime.timedelta(weeks=4):
            raise ValidationError(_('无效日期 - 续借时间超过4周'))
            
        return data

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death', 'bio', 'photo']
        labels = {
            'first_name': _('名'),
            'last_name': _('姓'),
            'date_of_birth': _('出生日期'),
            'date_of_death': _('死亡日期'),
            'bio': _('作者简介'),
            'photo': _('照片'),
        }
        widgets = {
            'date_of_birth': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'date_of_death': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'bio': forms.Textarea(attrs={'class': 'form-control'}),
        }

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'author', 'summary', 'isbn', 'genre', 'cover', 'price', 'publication_date']
        widgets = {
            'summary': forms.Textarea(attrs={'class': 'form-control'}),
            'publication_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'genre': forms.CheckboxSelectMultiple(),
        }

class ReviewForm(forms.ModelForm):
    class Meta:
        model = Review
        fields = ['rating', 'comment']
        widgets = {
            'comment': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'rating': forms.NumberInput(attrs={'class': 'form-control', 'min': 1, 'max': 5}),
        }
        labels = {
            'rating': _('评分 (1-5)'),
            'comment': _('评论'),
        }

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['bio', 'avatar', 'reading_preferences']
        widgets = {
            'bio': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'reading_preferences': forms.CheckboxSelectMultiple(),
        }
        labels = {
            'bio': _('个人简介'),
            'avatar': _('头像'),
            'reading_preferences': _('阅读偏好'),
        }

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name']
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'readonly': 'readonly'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'first_name': forms.TextInput(attrs={'class': 'form-control'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control'}),
        }
        
class SearchForm(forms.Form):
    query = forms.CharField(label=_('搜索'), max_length=100, required=False)
    genre = forms.ModelChoiceField(queryset=Genre.objects.all(), required=False, label=_('类型'))
    rating = forms.ChoiceField(choices=[(i, i) for i in range(1, 6)], required=False, label=_('最低评分')) 

class RegisterForm(UserCreationForm):
    email = forms.EmailField(
        max_length=254,
        required=True,
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': '请输入有效的电子邮箱'}),
        help_text='请输入有效的电子邮箱地址',
        label='电子邮箱'
    )
    
    first_name = forms.CharField(
        max_length=30,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入您的名字'}),
        label='名字'
    )
    
    last_name = forms.CharField(
        max_length=30,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入您的姓氏'}),
        label='姓氏'
    )
    
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2')
        labels = {
            'username': _('用户名'),
        }
        
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        # 自定义表单字段的样式
        self.fields['username'].widget.attrs.update({'class': 'form-control', 'placeholder': '请输入用户名'})
        self.fields['password1'].widget.attrs.update({'class': 'form-control', 'placeholder': '请输入密码'})
        self.fields['password2'].widget.attrs.update({'class': 'form-control', 'placeholder': '请再次输入密码'})
        self.fields['username'].label = '用户名'
        self.fields['password1'].label = '密码'
        self.fields['password2'].label = '确认密码' 